<?php
/**
 * 用户个人资料控制器
 */
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/classes/User.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    setFlashMessage('error', '请先登录');
    redirect('login.php');
}

$userId = $_SESSION['user_id'];
$user = new User();
$userData = $user->getUser($userId);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理个人资料更新
    if (isset($_POST['update_profile'])) {
        $nickname = sanitizeInput($_POST['nickname'] ?? '');
        $bio = sanitizeInput($_POST['bio'] ?? '');
        
        $updateData = [
            'nickname' => $nickname,
            'bio' => $bio
        ];
        
        // 处理头像上传
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/avatars/';
            
            // 确保上传目录存在
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            // 获取文件信息
            $fileName = $_FILES['avatar']['name'];
            $fileTmpName = $_FILES['avatar']['tmp_name'];
            $fileSize = $_FILES['avatar']['size'];
            $fileError = $_FILES['avatar']['error'];
            
            // 获取文件扩展名
            $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            
            // 允许的文件类型
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif'];
            
            // 检查文件类型
            if (in_array($fileExt, $allowedExts)) {
                // 生成唯一文件名
                $newFileName = uniqid('avatar_') . '.' . $fileExt;
                $destination = $uploadDir . $newFileName;
                
                // 移动上传的文件
                if (move_uploaded_file($fileTmpName, $destination)) {
                    $updateData['avatar'] = $destination;
                } else {
                    $uploadError = '头像上传失败，请稍后再试';
                }
            } else {
                $uploadError = '只允许上传JPG、JPEG、PNG或GIF格式的图片';
            }
        }
        
        // 更新个人资料
        $result = $user->updateProfile($userId, $updateData);
        
        if ($result['status']) {
            setFlashMessage('success', $result['message']);
            // 重新获取用户数据
            $userData = $user->getUser($userId);
        } else {
            $error = $result['message'];
        }
        
        if (isset($uploadError)) {
            $error = $uploadError;
        }
    }
    
    // 处理密码修改
    if (isset($_POST['change_password'])) {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        // 验证新密码与确认密码是否一致
        if ($newPassword !== $confirmPassword) {
            $passwordError = '新密码与确认密码不一致';
        } else {
            $result = $user->changePassword($userId, $currentPassword, $newPassword);
            
            if ($result['status']) {
                setFlashMessage('success', $result['message']);
            } else {
                $passwordError = $result['message'];
            }
        }
    }
}

// 初始化变量
$error = $error ?? null;
$passwordError = $passwordError ?? null;

// 加载视图
$pageTitle = '个人资料';
extract(compact('userData', 'error', 'passwordError', 'pageTitle'));
require_once __DIR__ . '/views/user/profile.php';
